package com.example.spring;

import com.example.spring.config.InstantiationProcessProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author yanzhao
 * @date 2022/11/10 14:55
 * @since 1.0.0
 */
@Component
public class InstantiationAwareBeanPostProcessorTest implements InstantiationAwareBeanPostProcessor {

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
//        if (beanClass.equals(BeforeInstantiation.class)) {
//            return ProxyUtil.getProxy(beanClass);
//        }
        return null;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if (beanName.equals("instantiationProcessProperties") && bean.getClass().equals(InstantiationProcessProperties.class)) {
            final MutablePropertyValues propertyValues;

            if (pvs instanceof MutablePropertyValues) {
                propertyValues = (MutablePropertyValues) pvs;
            } else {
                propertyValues = new MutablePropertyValues();
            }
            // 等价于 <property name="number" value="1" />
            propertyValues.addPropertyValue("name", "填充的属性");
            if (propertyValues.contains("desc")) {
                // PropertyValue value 是不可变的
                propertyValues.removePropertyValue("desc");
            }
            propertyValues.addPropertyValue("desc", "更换的属性");
            return propertyValues;
        }

        return null;
    }
}
